#!/bin/bash

if test -z $1 -o -z $2; then
	echo "$0 [#iterations] [#particles]"
	exit -1
fi

## execute swarm
java -Xmx2g -Xms2g -jar ../swarm-0.1.jar $1 $2 > saida.txt

## clean
rm -f data*.txt

## parsing relevant info.
cat saida.txt | grep ^[[:digit:]] | sed s/\(//g | sed s/\)//g | sed s/+//g | sed s/=//g | sed s/\\^2//g | sed s/E//g | sed s/\ \ /\ /g > data.txt

# organize result to gnuplot
max=$(cat data.txt | cut -d' ' -f1 | uniq | tail -1)
if test $max -lt 1; then
	echo "Number of iterations invalid!"
	exit -1
fi

for ((i=0; i<=$max; i++)); do
	grep "^$i " data.txt >> data$i.txt
	# echo >> data$i.txt
done 

## show global best
tail -3 saida.txt

## plotting chart
echo "#!/opt/local/bin/gnuplot" > plot.gp
echo "clear" >> plot.gp
echo "reset" >> plot.gp
echo "set xrange [-2:2]" >> plot.gp
echo "set yrange [-2:2]" >> plot.gp
echo "set zrange [-2:2]" >> plot.gp
echo "set terminal gif animate delay 50" >> plot.gp
echo "set output \"animate.gif\"" >> plot.gp

# function="x**2+y**2"
# function="sin(sqrt(x**2+y**2)) * y**2"
# function="(x*y)-(x**2+y**2)"
# function="x*y"
function="sin(x**2+y**2)"
for ((i=0; i<=$max; i++)); do
	# echo -ne "\nsplot" >> plot.gp
	# while read line; do 
	#    	x=$(echo $line | cut -d' ' -f3)
	#    	y=$(echo $line | cut -d' ' -f4)
	# 		if [ ! -z $x ]; then 
	# 			echo -ne " sin(sqrt(($x)**2+($y)**2))/sqrt(($x)**2+($y)**2) with points," >> plot.gp
	# 		fi
	# done < data$i.txt
	# echo -e '\n' >> plot.gp
	echo " splot $function linecolor rgb \"grey\", \"data$i.txt\" using 3:4:5 with points linecolor rgb \"red\"" >> plot.gp
done

sed 's/,$//g' plot.gp > plot.tmp
mv plot.tmp plot.gp
chmod +x plot.gp
./plot.gp
